<?php



namespace app\mini\model;



use think\facade\Db;

use app\common\traits\ActionRecordTrait;

use think\Model;

use app\admin\model\Access;

use app\crm\model\CustomerLossModel;

use app\crm\model\ReserveandLost;


class PersonCustomer extends Model

{

	use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'customer';

    protected $deleteTime = 'deleted_at';

    protected $defaultSoftDelete = 0;



    /**

     * 获取服务记录列表

     * @param  array $request 请求参数

     * @return array

     * @author hz

     * @create 2021-10-19

     */

    public function getCustomerList($request)

    {
        $startTime = strtotime(date('Y-m-01',time()));
        $endTime = strtotime(date('Y-m-t 23:59:59',time()));

        try {
            
            // if(!$request['person_id'])

            // {

            //     return ['error' => '您还未认证,请先认证'];

            // }

            $where   = [];

            $searchValue = $request['searchValue'] ?? ''; // 查询条件

            $person_id = $request['person_id'] ?? 0; // 员工id(shop_person表的id)

            $user_id = $request['user_id'] ?? 0; // 登陆人id(admin_user表的id)

            //查询该员工的 查询权限和客户档案
			$userList = Db::name('admin_user')->alias('u')
                        ->join('shop_person s', 'u.shop_person_id=s.id', 'LEFT')
                        ->where('u.id','=',$user_id)
                        ->where('u.is_status','=',0)
                        ->column('u.type,u.structure_name,u.structure_id,u.shop_person_id,s.position_id');

            //判断客服 归属的 只能查看自己的客户档案
			if($userList[0]['type'] ==1  && $userList[0]['structure_id'] =='8' ){
				array_push($where,['operator','=',$user_id]);
			}
			//判断店面护理师 只能查看自己名下的 客户档案
			if($userList[0]['type'] ==3  && $userList[0]['position_id'] =='9' ){
				array_push($where,['nurse_id','=',$userList[0]['shop_person_id']]);
			}

            // $shopIds = json_decode($request['shopIds'],true);
            $shopIds = json_decode($request['shopIds'],true) ?? array();
            // exit;
            array_push($where,['shop_id','in',$shopIds]);

            

            if(!empty($searchValue)){
                array_push($where,['customer_name|telephone','like',"$searchValue%"]);
            }

            $customerLossModel = new CustomerLossModel();
            // $customerLossModel = new ReserveandLost();

            $date = date('Y-m-d',time());

            $type = $request['type'] ?? '';
            if($type == 'noComeIn'){
                array_push($where,['first_time','<',1]);
                array_push($where,['second_time','<',1]);
                array_push($where,['create_time','between',"$startTime,$endTime"]);
            }else if($type == 'liushiyj'){
                // echo "<pre>";
                // print_r($request);
                // echo "</pre>";
                // exit;

                // 流失预警
                
                

                // echo "<pre>";
                // print_r($request);
                // echo "</pre>";
                // exit;

                // $liushiyujing = [
                //     'is_join_shop' => 4,
                //     'shopIds' => $shopIds,
                //     'user_id' => $request['user_id'],
                //     'onlyList' => 'yes',
                //     'customer_name' => $searchValue,
                //     'page' => $request['page'],
                //     'limit' => $request['limit'],
                // ];

                
                // $cid  = $customerLossModel->getDataList($liushiyujing);
                // $list      = $dataList['list'];
                // $dataCount = $dataList['dataCount'];
                // $cid    = array_values(array_unique(array_column($list, 'id')));


                // ---------------------------------------------------------------------------------------------
                
                $request['shopIds'] = $shopIds;
                $request['is_join_shop'] = '4';
                $cid  = $customerLossModel->getDataList1($request);

                $dataCount = count($cid);

                array_push($where,['id','in',$cid]);

            }else if($type == 'liushikh'){
                // 流失客户
                // $liushikehu = [
                //     'is_join_shop' => 3,
                //     'shopIds' => $shopIds,
                //     'user_id' => $request['user_id'],
                //     'onlyList' => 'yes',
                //     'customer_name' => $searchValue,
                //     'page' => $request['page'],
                //     'limit' => $request['limit'],
                // ];

                // $dataList = $customerLossModel->getDataList($liushikehu);
                // $list = $dataList['list'];
                // $dataCount = $dataList['dataCount'];

                // $cid    = array_values(array_unique(array_column($list, 'id')));

                // ---------------------------------------------------------------------------------------------
                $request['shopIds'] = $shopIds;
                $request['is_join_shop'] = '3';
                $cid  = $customerLossModel->getDataList1($request);

                $dataCount = count($cid);

                array_push($where,['id','in',$cid]);

            }else if($type == 'noCJ'){
                array_push($where,['cj_time','<',1]);
                array_push($where,['first_time|second_time','between',"$startTime,$endTime"]);
            }else if($type == 'birthday'){
                $birthdayStr = strtotime('+1 week');
                $nowTime = time();
                array_push($where,['membership_leve','>',0]);
                array_push($where,['birthday','between',"$nowTime,$birthdayStr"]);
            }else{
                
            }
            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;
            if($type == 'liushiyj' || $type == 'liushikh'){
                $list = Db::name('customer')->where($where)->select()->toArray();
            }else{

                
                $dataCount = Db::name('customer')->where($where)->count();
                $list = Db::name('customer')->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();

                // echo "<pre>";
                // print_r($list);
                // echo "</pre>";
                // exit;
            }

            // echo "<pre>";
            // print_r($list);
            // echo "</pre>";
            // exit;


            // 获取客户门店归属
            $shop_ids = array_values(array_unique(array_column($list,'shop_id')));

            $where = [];

            array_push($where,['shop_id','in',$shop_ids]);
            // echo "<pre>";
            // print_r($shop_ids);
            // echo "</pre>";
            // exit;
            

            $shopList = Db::name('shop')->where($where)->column('shop_name','shop_id');

            // 获取客户微信授权信息
            $customerIds = array_values(array_unique(array_column($list,'id')));

            $where = [];

            array_push($where,['customerId','in',$customerIds]);

            $wxInfo = Db::name('mini_program_fans')->where($where)->column('openId,nickName,avatarUrl','customerId');
           
            

            foreach ($list as $key => $value) {

                $list[$key]['shop_name'] = $shopList[$value['shop_id']] ?? '';


                if($value['membership_leve'] == '1'){
                    $list[$key]['vipName'] = '白玉兰';
                }elseif($value['membership_leve'] == '2'){
                    $list[$key]['vipName'] = '紫玉兰';
                }elseif($value['membership_leve'] == '3'){
                    $list[$key]['vipName'] = '金玉兰';
                }else{
                    $list[$key]['vipName'] = '非会员';
                }

                $comeInTime = $value['second_time']>0 ? $value['second_time'] : $value['first_time'];

                $list[$key]['comeInTime'] = $comeInTime > 0 ? date('Y-m-d',$comeInTime) : '未进店';

                if($value['member_classification'] == '0'){
                    $list[$key]['clv'] = '';
                }elseif($value['member_classification'] == '70'){
                    $list[$key]['clv'] = 'D类';
                }elseif($value['member_classification'] == '71'){
                    $list[$key]['clv'] = 'C类';
                }elseif($value['member_classification'] == '72'){
                    $list[$key]['clv'] = 'B类';
                }else{
                    $list[$key]['clv'] = 'A类';
                }

                // 微信授权信息
                $list[$key]['avatarUrl'] = $wxInfo[$value['id']]['avatarUrl'] ?? '';
            }

            



            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return ['data' => $data];

        } catch (\Exception $e) {

            return ['error' => $e->getMessage()];

        }

    }

    public function getCustomerInfo($request)
    {
        $customerId = $request['id'];

        $where = [];

        array_push($where,['id','=',$customerId]);

        $info = Db::name('customer')->where($where)->select()->toArray();

        // 最近进店时间
        if($info[0]['final_consumption']>0 || $info[0]['final_service']>0){
            $lastTime = $info[0]['final_consumption'] > $info[0]['final_service'] ? date('Y-m-d',$info[0]['final_consumption']) : date('Y-m-d',$info[0]['final_service']);
        }else{
            $lastTime = '客户未进店';
        }

        
        // 门店
        $shopinfo = Db::name('shop')->where('shop_id',$info[0]['shop_id'])->select()->toArray();

        $lastText = substr($shopinfo[0]['shop_name'],-3);

        if($lastText == '店'){
            $shopName = '欣奕除疤'.$shopinfo[0]['city_name'].$shopinfo[0]['shop_name'];
        }else{
            $shopName = '欣奕除疤'.$shopinfo[0]['city_name'].$shopinfo[0]['shop_name'].'店';
        }

        // 3个月内进店次数
        $time2 = strtotime('-3 month');

        $orderWhere = [];

        array_push($orderWhere,['uid','=',$customerId]);

        array_push($orderWhere,['deal_time','>=',$time2]);

        $refund = Db::name('shop_refund_order')
                ->where($orderWhere)
                ->where('status','2')
                ->where('refund_type','101.02')
                ->where('type','3')
                ->column('deal_time');
        
        // echo $refund;

        $order = Db::name('shop_order')
                ->where($orderWhere)
                ->where('status','2')
                ->column('deal_time');

        // echo $order;

        $service = Db::name('service_log')->where('customer_id',$customerId)->where('create_time','>=',$time2)->column('create_time');

        $comeInTimes = [];
        
        foreach ($refund as $key => $value) {
            $thisTime = date('Y-m-d',$value);
            if(in_array($thisTime,$comeInTimes)){

            }else{
                array_push($comeInTimes,$thisTime);
            }
        }

        foreach ($order as $key => $value) {
            $thisTime = date('Y-m-d',$value);
            if(in_array($thisTime,$comeInTimes)){

            }else{
                array_push($comeInTimes,$thisTime);
            }
        }

        foreach ($service as $key => $value) {
            $thisTime = date('Y-m-d',$value);
            if(in_array($thisTime,$comeInTimes)){

            }else{
                array_push($comeInTimes,$thisTime);
            }
        }
        
        $jindianN = count($comeInTimes);

        // 账户预存
        $balanceBh = Db::name('customer_balance')->where('customer_id',$customerId)->where('balance_category_id','1')->find();

        $BH = bcadd($balanceBh['money'],$balanceBh['complimentary_money'],2);

        $balanceXm = Db::name('customer_balance')->where('customer_id',$customerId)->where('balance_category_id','2')->find();

        $XM = bcadd($balanceXm['money'],$balanceXm['complimentary_money'],2);

        $balanceTotle = bcadd($BH,$XM,2);

        // echo "<pre>";
        // print_r($balanceBh);
        // echo "</pre>";
        // exit;

        // 客户微信头像
        $where = [];

        array_push($where,['customerId','=',$customerId]);
        

        $wxInfo = Db::name('mini_program_fans')->where($where)->field('avatarUrl')->find();
        //     echo "<pre>";
        // print_r($wxInfo);
        // echo "</pre>";
        // exit;
       
        return $result = [
            'lastTime' => $lastTime,
            'shopName' => $shopName,
            'jindianN' => $jindianN,
            'balanceTotle' => $balanceTotle,
            'BH' => $BH,
            'XM' => $XM,
            'avatarUrl' => $wxInfo['avatarUrl'] ?? '0',
        ];
        
    }



}